define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuerp/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {

            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;
                var form = layui.form;

                table.render({
                    elem: '#table'
                    ,url:'kuerp/goods_sales_profit/index'
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows //解析数据列表
                        };
                    }
                    ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    ,defaultToolbar: [
                        {name:'filter', title: __('Filter')}, // 列筛选
                         {
                            name: 'exports',
                            title: __('Exports'),
                            onClick: function(obj) {
                              // 获得数据并清除临时字段
                              var data = table.clearCacheKey(obj.data);
                              // 当前示例配置项
                              var options = obj.config;

                              if(data.length > 0 || Object.keys(data).length > 0){
                                table.exportFile(options.id, null, 'csv');
                              }else{
                                layer.msg(__('No data'));
                              }
                             
                            }
                          },
                        {name:'print', title: __('Print')} // 打印
                    ]
                    ,page: true
                    ,layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                    ,page: {
                        prev: __('Previous'),
                        next: __('Next'),
                        first: __('First'),
                        last: __('Last'),
                        skipText: [__('Go to page'), '', __('Confirm')],
                        countText: [__('Total') + ' ',' ' +  __('Records')],
                        limitTemplet: function(item) {
                            return item + ' ' + __('entries');
                        }
                    }
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,text: {
                        none: __('No data'),
                        loading: __('Loading...'),
                    }
                    ,where: {
                        filter:JSON.stringify(getSearch()),
                        op:JSON.stringify(getOp()),
                    }
                    ,cols: [[
                        {field: 'c_type_name', title: __('Customer_category')},
                        {field: 'customer_code', title: __('Customer_code'),sort:true},
                        {field: 'customer_name', title: __('Customer_name')},
                        {field: 'count', title: __('Sales_count'),sort:true},
                        {field: 'basic_nmber', title: __('Sales_basic_quantity'),sort:true},
                        {field: 'all_money', title: __('Sales_amount'),sort:true},
                        {field: 'tax_money', title: __('Tax_amount'),sort:true},
                        {field: 'money_tax_price', title: __('Price_tax_total'),sort:true},
                        {field: 'unit_cost', title: __('Unit_cost'),sort:true},
                        {field: 'cost_all', title: __('Sales_cost'),sort:true},
                        {field: 'profit', title: __('Sales_profit'),sort:true},
                        {field: 'profit_rate', title: __('Profit_rate'),sort:true},
                    ]]
                    ,done: function(res, curr, count){
                        if (res.count == 0 && !searchStatus) {
                            var html = '<div class="layui-none no-results"><span>' + __('Please enter search criteria and click search') + '</span></div>';
                            $(".layui-table-main").html(html);
                        }
                    }
                });

                //头工具栏事件
                table.on('toolbar(table)', function(obj){
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                    }
                });

                //搜索事件
                $('#search').on('click', function () {
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify(getOp()),
                        }
                        ,page: {
                            curr: 1,
                            prev: __('Previous'),
                            next: __('Next'),
                            first: __('First'),
                            last: __('Last'),
                            skipText: [__('Go to page'), '', __('Confirm')],
                            countText: [__('Total') + ' ',' ' +  __('Records')],
                            limitTemplet: function(item) {
                                return item + ' ' + __('entries');
                            }
                        }
                    });
                });
                var searchStatus = false;
                function getSearch() {
                    var search = {};
                    var purchase_type = $('#purchase_type').val();
                    if(purchase_type!=''){
                        search.purchase_type = purchase_type;
                    }
                    var customerType = $('#customerType').val();
                    if(customerType!=''){
                        search.customerType = customerType;
                    }
                    var customerList = $('#customerList').val();
                    if(customerList!=''){
                        search.customerList = customerList;
                    }
                    var goodsType = $('#goodsType').val();
                    if(goodsType!=''){
                        search.goodsType = goodsType;
                    }
                    var goods_code = $('#goods_code').val();
                    if(goods_code!=''){
                        search.goods_code = goods_code;
                    }
                    var purchase_time = $('#purchase_time').val();
                    if(purchase_time!=''){
                        search.purchase_time = purchase_time;
                    }
                    if(customerType=='' && customerList=='' && purchase_time==''){
                        searchStatus = false;
                        search.id = 1;
                    }else{
                        searchStatus = true;
                    }
                    return search;
                }
                function getOp() {
                    var op = {};
                    op.goods_code = 'LIKE';
                    op.purchase_time = 'RANGE';
                    op.id = '<';
                    return op;
                }

                form.on('select(customerType)', function(data){
                    var type = data.value;
                    $('.search_type').hide();
                    $('.search_type'+type).show();
                    if(type==2){
                        $('.layui-tab-item1').removeClass('layui-show');
                        $('.layui-tab-item2').addClass('layui-show')
                    }else{
                        $('.layui-tab-item2').removeClass('layui-show');
                        $('.layui-tab-item1').addClass('layui-show')
                    }
                });
            });

            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;
                var form = layui.form;

                table.render({
                    elem: '#table2'
                    ,url:'kuerp/goods_sales_profit/index2'
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows //解析数据列表
                        };
                    }
                    ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    ,defaultToolbar: [
                        {name:'filter', title: __('Filter')}, // 列筛选
                         {
                            name: 'exports',
                            title: __('Exports'),
                            onClick: function(obj) {
                              // 获得数据并清除临时字段
                              var data = table.clearCacheKey(obj.data);
                              // 当前示例配置项
                              var options = obj.config;

                              if(data.length > 0 || Object.keys(data).length > 0){
                                table.exportFile(options.id, null, 'csv');
                              }else{
                                layer.msg(__('No data'));
                              }
                             
                            }
                          },
                        {name:'print', title: __('Print')} // 打印
                    ]
                    ,page: true
                    ,layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                    ,page: {
                        prev: __('Previous'),
                        next: __('Next'),
                        first: __('First'),
                        last: __('Last'),
                        skipText: [__('Go to page'), '', __('Confirm')],
                        countText: [__('Total') + ' ',' ' +  __('Records')],
                        limitTemplet: function(item) {
                            return item + ' ' + __('entries');
                        }
                    }
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,text: {
                        none: __('No data'),
                        loading: __('Loading...'),
                    }
                    ,where: {
                        filter:JSON.stringify(getSearchs()),
                        op:JSON.stringify(getOps()),
                    }
                    ,cols: [[
                        {field: 'c_type_name', title: __('Product_category')},
                        {field: 'customer_code', title: __('Product_code'),sort:true},
                        {field: 'customer_name', title: __('Product_name')},
                        {field: 'count', title: __('Sales_count'),sort:true},
                        {field: 'basic_nmber', title: __('Sales_basic_quantity'),sort:true},
                        {field: 'all_money', title: __('Sales_amount'),sort:true},
                        {field: 'tax_money', title: __('Tax_amount'),sort:true},
                        {field: 'money_tax_price', title: __('Price_tax_total'),sort:true},
                        {field: 'unit_cost', title: __('Unit_cost'),sort:true},
                        {field: 'cost_all', title: __('Sales_cost'),sort:true},
                        {field: 'profit', title: __('Sales_profit'),sort:true},
                        {field: 'profit_rate', title: __('Profit_rate'),sort:true},
                    ]]
                    ,done: function(res, curr, count){
                        if (res.count == 0 && !searchStatus2) {
                            var html = '<div class="layui-none no-results"><span>' + __('Please enter search criteria and click search') + '</span></div>';
                            $(".layui-table-main").html(html);
                        }
                    }
                });

                //头工具栏事件
                table.on('toolbar(table2)', function(obj){
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table2', []);
                            break;
                    }
                });

                //搜索事件
                $('#search').on('click', function () {
                    table.reload('table2', {
                        where: {
                            filter:JSON.stringify(getSearchs()),
                            op:JSON.stringify(getOps()),
                        }
                        ,page: {
                            curr: 1,
                            prev: __('Previous'),
                            next: __('Next'),
                            first: __('First'),
                            last: __('Last'),
                            skipText: [__('Go to page'), '', __('Confirm')],
                            countText: [__('Total') + ' ',' ' +  __('Records')],
                            limitTemplet: function(item) {
                                return item + ' ' + __('entries');
                            }
                        }
                    });
                });
                var searchStatus2 = false;
                function getSearchs() {
                    var search = {};
                    var purchase_type = $('#purchase_type').val();
                    if(purchase_type!=''){
                        search.purchase_type = purchase_type;
                    }
                    var customerType = $('#customerType').val();
                    if(customerType!=''){
                        search.customerType = customerType;
                    }
                    var customerList = $('#customerList').val();
                    if(customerList!=''){
                        search.customerList = customerList;
                    }
                    var goodsType = $('#goodsType').val();
                    if(goodsType!=''){
                        search.goodsType = goodsType;
                    }
                    var goods_code = $('#goods_code').val();
                    if(goods_code!=''){
                        search.goods_code = goods_code;
                    }
                    var purchase_time = $('#purchase_time').val();
                    if(purchase_time!=''){
                        search.purchase_time = purchase_time;
                    }
                    if(goodsType=='' && goods_code=='' && purchase_time==''){
                        searchStatus2 = false;
                        search.id = 1;
                    }else{
                        searchStatus = true;
                    }
                    return search;
                }
                function getOps() {
                    var op = {};
                    op.goods_code = 'LIKE';
                    op.purchase_time = 'RANGE';
                    op.id = '<';
                    return op;
                }

                form.on('select(customerType)', function(data){
                    var type = data.value;
                    $('.search_type').hide();
                    $('.search_type'+type).show();
                    if(type==2){
                        $('.layui-tab-item1').removeClass('layui-show');
                        $('.layui-tab-item2').addClass('layui-show')
                    }else{
                        $('.layui-tab-item2').removeClass('layui-show');
                        $('.layui-tab-item1').addClass('layui-show')
                    }
                });
            });
            $('.search_type2').hide();
            Controller.api.bindevent();
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {

                layui.use(['table','form'], function(){
                    var supplyer_div = xmSelect.render({
                        el: '#customers_ids',
                        filterable: true,
                        paging: true,
                        language: Config.lang == 'zh-cn' ? 'cn' : 'en',
                        tips: __('Please_select_customer'),
                        pageSize: 5,
                        // remoteSearch: true,
                        pageRemote: true,
                        remoteMethod: function (val, cb, show, pageIndex) {
                            $.ajax({
                                url: "kuerp/customers/index",
                                type: 'GET',
                                crossOrigin: true,
                                dataType: 'json',
                                cache: false,
                                async: true,
                                data: {
                                    keywords: val,
                                    filter:JSON.stringify({"customer_name":val}),
                                    op:JSON.stringify({"customer_name":'like'}),
                                    page: pageIndex,
                                    limit: 5
                                },
                                success: function (data) {
                                    var TotalCount = data.total;
                                    var Pages = Math.ceil(TotalCount/5);
                                    var list = [];
                                    $(data.rows).each(function (k,v) {
                                        var row = [];
                                        row['name'] = v.customer_name;
                                        row['value'] = v.id;
                                        list.push(row)
                                    });
                                    setTimeout(function () {
                                        cb(list, Pages)
                                    }, 100)
                                },
                                error: function (data) {
                                    cb([], 0);
                                }
                            });
                        },
                        on: function(data){
                            var arr = data.arr;
                            var change = data.change;
                            var isAdd = data.isAdd;
                            if(!isAdd){
                                $('#customerList').val('');
                            }
                            // if(change.length>0){
                            //     for (let i in arr){
                            //         if(change[0].parentId==arr[i].parentId){
                            //             arr.splice(i,1,change[0]);
                            //         }
                            //     }
                            // }
                            if(arr.length>0){
                                var ids = '';
                                $(arr).each(function (k,v) {
                                    ids = ids+v['value']+',';
                                });
                                $('#customerList').val(ids);
                                // if(arr[0]['value']!=undefined){
                                //     $('#customerList').val(arr[0]['value']);
                                // }
                            }
                            return Array.from(new Set(arr));
                        },
                    });

                    var goods_div = xmSelect.render({
                        el: '#goods_codes',
                        filterable: true,
                        paging: true,
                        language: Config.lang == 'zh-cn' ? 'cn' : 'en',
                        tips: __('Please_select_goods'),
                        pageSize: 5,
                        // remoteSearch: true,
                        pageRemote: true,
                        remoteMethod: function (val, cb, show, pageIndex) {
                            $.ajax({
                                url: "kuerp/goods/index",
                                type: 'GET',
                                crossOrigin: true,
                                dataType: 'json',
                                cache: false,
                                async: true,
                                data: {
                                    keywords: val,
                                    page: pageIndex,
                                    limit: 5
                                },
                                success: function (data) {
                                    var TotalCount = data.total;
                                    var Pages = Math.ceil(TotalCount/5);
                                    var list = [];
                                    $(data.rows).each(function (k,v) {
                                        var row = [];
                                        row['name'] = v.goods_name;
                                        row['value'] = v.goods_code;
                                        list.push(row)
                                    });
                                    setTimeout(function () {
                                        cb(list, Pages)
                                    }, 100)
                                },
                                error: function (data) {
                                    cb([], 0);
                                }
                            });
                        },
                        on: function(data){
                            var arr = data.arr;
                            var change = data.change;
                            var isAdd = data.isAdd;
                            if(!isAdd){
                                $('#goods_code').val('');
                            }
                            // if(change.length>0){
                            //     for (let i in arr){
                            //         if(change[0].parentId==arr[i].parentId){
                            //             arr.splice(i,1,change[0]);
                            //         }
                            //     }
                            // }
                            if(arr.length>0){
                                var ids = '';
                                $(arr).each(function (k,v) {
                                    ids = ids+v['value']+',';
                                });
                                $('#goods_code').val(ids);
                                // if(arr[0]['value']!=undefined){
                                //     $('#goods_code').val(arr[0]['value']);
                                // }
                            }
                            return Array.from(new Set(arr));
                        },
                    });
                });

                layui.use('laydate', function(){
                    var laydate = layui.laydate;
                    laydate.render({
                         lang: Config.lang == 'zh-cn' ? 'cn' : 'en',
                        elem: '#purchase_time',
                        type: 'datetime',
                        range: true,
                        lang: 'en'
                    });
                });
                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    parent.location.reload();
                });
            }
        }
    };
    return Controller;
});